package com.heima.kafka;

import org.apache.kafka.clients.producer.*;
import org.junit.Test;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class ProducerQuickStart {

    @Test
    public void sendMsg() throws ExecutionException, InterruptedException {
        //1配种kafka
        Properties properties = new Properties();
        properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);


        //2. 创建生产者
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3. 发送消息
        ProducerRecord<String, String> record = new ProducerRecord<>("itheima-topic","100001","hello kafka");
        Future<RecordMetadata> response = producer.send(record);
        System.out.println(response.get().offset());

        //4. 关闭生产者

        producer.close();
    }

    @Test
    public void sendMsg1() throws ExecutionException, InterruptedException {
        //1配种kafka
        Properties properties = new Properties();
        properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);

        properties.put(ProducerConfig.ACKS_CONFIG, "1");
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "gzip");


        //2. 创建生产者
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3. 发送消息
        ProducerRecord<String, String> record = new ProducerRecord<>("itheima-topic","100001","hello kafka");
        Future<RecordMetadata> response = producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata metadata, Exception e) {
                if(null != e){
                    e.printStackTrace();
                }

                System.out.println(metadata.offset());
            }
        });

        //4. 关闭生产者

        producer.close();
    }
}
